package com.xingxing.Service;

import com.google.gson.Gson;
import com.xingxing.Bean.User;
import com.xingxing.Dao.UserDao;
import com.xingxing.Util.HashUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther XingxingLu
 * @date 2022-06-08 9:37
 */
@WebServlet(name = "EditPassword", value = "/EditPassword")
public class EditPassword extends HttpServlet {
    public EditPassword() {
        super();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(
                new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
        String temp;
        while ((temp = br.readLine()) != null) {
            sb.append(temp);
        }
        br.close();
        Map<String, Object> map = new HashMap<>();
        map = new Gson().fromJson(sb.toString(), map.getClass());
        User user = UserDao.find((String) map.get("userAccount"));
        map.put("userPassword", HashUtil.getSHA256StrJava((String) map.get("userAccount") + (String) map.get("userPassword")));
        user.setUserPassword((String) map.get("userPassword"));
        map.clear();
        if (UserDao.updatePassword(user)) {
            map.put("status", "修改成功");
        } else {
            map.put("status", "修改失败");
        }
        String str = new Gson().toJson(map);
        out.println(str);
        out.flush();
        out.close();
    }

    public void destroy() {
        super.destroy();
    }
}
